#include <assert.h>
#include <fcntl.h>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/types.h>

/// @brief 默认请求
static const char *REQUEST = "GET /index.html HTTP/1.1\r\nConnection:keep-alive\r\n\r\nSTRESS TESTING";

int setNonblocking(int fd)
{
    int old_opt = fcntl(fd, F_GETFL);
    int new_opt = old_opt | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_opt);
    return old_opt;
}

void addFd(int epollfd, int fd)
{
    epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLOUT | EPOLLET | EPOLLERR;
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
    setNonblocking(fd);
}

/// @brief 向服务器写入数据
/// @param sockfd
/// @param buffer
/// @param len
/// @return
bool write_nbytes(int sockfd, const char *buffer, int len)
{
    int bytes_write = 0;
    printf("Write Out %d Bytes To Socket %d\n", len, sockfd);
    while (1)
    {
        bytes_write = send(sockfd, buffer, len, 0);
        if (bytes_write == -1)
            return false;
        else if (bytes_write == 0)
            return false;
        len -= bytes_write;
        buffer = buffer + bytes_write;
        if (len < 0)
            return true;
    }
}

/// @brief 从服务器读取数据
/// @param sockfd
/// @param buffer
/// @param len
/// @return
bool read_once(int sockfd, char *buffer, int len)
{
    int bytes_read = 0;
    memset(&buffer, '\0', len);
    bytes_read = recv(sockfd, buffer, len, 0);
    if (bytes_read == -1)
        return false;
    else if (bytes_read == 0)
        return false;
    printf("Read In %d Bytes From Socket %d With Content: %s\n", bytes_read, sockfd, buffer);
    return true;
}

/// @brief 根据并发数与服务器建立连接
/// @param epollfd 内核事件表
/// @param num 并发数
/// @param ip IP地址
/// @param port 端口
void start_conn(int epollfd, int num, const char *ip, int port)
{
    int ret = 0;
    sockaddr_in address;
    memset(&address, 0, sizeof(address));
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr(ip);
    address.sin_port = htons(port);

    // 生成指定范围内的随机小数
    std::default_random_engine e(time(NULL));
    std::uniform_real_distribution<double> num_r(0.001, 1);

    for (int i = 0; i < num; ++i)
    {
        sleep(num_r(e));
        int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_IP);
        printf("- Create Sock -\n");
        if (sockfd < 0)
            continue;
        if (connect(sockfd, (sockaddr *)&address, sizeof(address)) == 0)
        {
            printf("Build Connection %d\n", i);
            addFd(epollfd, sockfd);
        }
    }
}

/// @brief 关闭服务器连接
/// @param epollfd
/// @param sockfd
void close_conn(int epollfd, int sockfd)
{
    epoll_ctl(epollfd, EPOLL_CTL_DEL, sockfd, 0);
    close(sockfd);
}

int main(int argc, const char *argv[])
{
    if (argc < 4)
    {
        printf("Usage: %s [ip_address] [port_number] [concurrent_num]\n", argv[0]);
        return 1;
    }

    int epoll_fd = epoll_create(100);
    start_conn(epoll_fd, atoi(argv[3]), argv[1], atoi(argv[2]));

    epoll_event events[10000];
    char buffer[2048];
    while (1)
    {
        int fds = epoll_wait(epoll_fd, events, 10000, 2000);
        for (int i = 0; i < fds; ++i)
        {
            int sockfd = events[i].data.fd;
            if (events[i].events & EPOLLIN)
            {
                if (!read_once(sockfd, buffer, 2048))
                    close_conn(epoll_fd, sockfd);
                epoll_event event;
                event.data.fd = sockfd;
                event.events = EPOLLOUT | EPOLLET | EPOLLERR;
                epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sockfd, &event);
            }
            else if (events[i].events & EPOLLOUT)
            {
                if (!write_nbytes(sockfd, REQUEST, strlen(REQUEST)))
                    close_conn(epoll_fd, sockfd);
                epoll_event event;
                event.data.fd = sockfd;
                event.events = EPOLLIN | EPOLLET | EPOLLERR;
                epoll_ctl(epoll_fd, EPOLL_CTL_MOD, sockfd, &event);
            }
            else if (events[i].events & EPOLLERR)
            {
                close_conn(epoll_fd, sockfd);
            }
        }
    }
}
